package job.work.utils;

import lombok.Cleanup;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * lua脚本读取工具类
 *
 * @author zengchao
 */
public class LuaScripts {

    /**
     * lua脚本全路径
     */
    private static final String LUA_PATH_RESOURCE = "META-INF/lua/redis.lua";
    private static final String LUA_PATH_RESOURCE2 = "apiclient_cert.p12";
    private static final String ENCODE = "utf-8";

    private LuaScripts() {
    }


    /**
     * 可读取到jar包的资源
     *
     * @return
     * @throws IOException
     */
    public static String readLuaScript() throws IOException {
        ClassPathResource resource = new ClassPathResource(LUA_PATH_RESOURCE);
        @Cleanup InputStream inputStream = resource.getInputStream();
        return Inputstr2Str_Reader(inputStream, ENCODE);
    }

    public static InputStream withdraw() {
        try {
            ClassPathResource resource = new ClassPathResource(LUA_PATH_RESOURCE2);
            InputStream inputStream = resource.getInputStream();
            return inputStream;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String Inputstr2Str_Reader(InputStream in, String encode) throws IOException {
        String str = StringUtils.EMPTY;
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, encode));
        StringBuffer sb = new StringBuffer();
        while ((str = reader.readLine()) != null) {
            sb.append(str).append("\n");
        }
        return sb.toString();
    }
}
